<template>
  <div class="list-header">
    <div class="header-button" v-if="hasAuth(AUTH_CODE.MESSAGE_ACTION.ADD)">
      <u-button type="primary" @click="handleEdit()">
        新建模板
      </u-button>
    </div>
    <dynamics-filter
      label-width="auto"
      :wrapper-width="250"
      :setting="setting"
      :loading="listQuery.loading"
      @query="handleQuery"
    />
  </div>
  <div class="list-body">
    <div class="list-wrap">
      <u-table
        row-key="smsTaskTemplateId"
        show-pagination
        :data="listData"
        :columns="messageColumns"
        :loading="listQuery.loading"
        :pagination="{
          total: listQuery.total,
          current: listQuery.currentPage,
          pageSize: listQuery.pageSize,
          showTotal: true,
          showSizer: true,
          showElevator: true
        }"
        @change="handleTableChange"
      >
        <template #templateName="{ row }">
          <one-line-text :text="row.templateName" />
        </template>
        <template #strategyList="{ row }">
          <one-line-text :text="getUsedStrategy(row.strategyList)" />
        </template>
        <template #templateType>
          {{ "短信任务模板" }}
        </template>
        <template #status="{ row }">
          {{ filter("status", row.status) }}
        </template>
        <template #createTime="{ row }">
          {{ parseTime(row.createTime, "YYYY-MM-DD HH:mm:ss") }}
        </template>
        <template #updateTime="{ row }">
          {{ parseTime(row.updateTime, "YYYY-MM-DD HH:mm:ss") }}
        </template>
        <template #remark="{ row }">
          <one-line-text :text="row.remark" />
        </template>
        <template #action="{ row }">
          <u-tooltip title="查看" v-if="hasAuth(AUTH_CODE.MESSAGE_ACTION.VIEW)">
            <u-button
              type="text"
              icon="view-detail"
              class="m-r-1 action-button"
              @click="handleView(row, 'view')"
            />
          </u-tooltip>
          <u-tooltip title="编辑" v-if="hasAuth(AUTH_CODE.MESSAGE_ACTION.EDIT)">
            <u-button
              type="text"
              icon="edit"
              class="m-r-1 action-button"
              @click="handleEdit(row)"
            />
          </u-tooltip>
          <u-pop-confirm
            v-if="row.status === 1 && hasAuth(AUTH_CODE.MESSAGE_ACTION.ENABLE)"
            title="确定禁用模板?"
            cancel-text="取消"
            ok-text="确认"
            placement="left"
            @confirm="handleForbid(row, 2)"
          >
            <u-tooltip title="禁用">
              <u-button
                type="text"
                icon="forbid"
                class="m-r-1 action-button"
                :disabled="!!row.strategyList"
              />
            </u-tooltip>
          </u-pop-confirm>
          <u-pop-confirm
            v-if="
              row.status === 2 || (row.status === 3 && hasAuth(AUTH_CODE.MESSAGE_ACTION.ENABLE))
            "
            title="确定启用模板?"
            cancel-text="取消"
            ok-text="确认"
            placement="left"
            @confirm="handleForbid(row, 1)"
          >
            <u-tooltip title="启用">
              <u-button type="text" icon="play" class="m-r-1 action-button" />
            </u-tooltip>
          </u-pop-confirm>
          <u-pop-confirm
            v-if="hasAuth(AUTH_CODE.MESSAGE_ACTION.DELETE)"
            title="确定删除?"
            cancel-text="取消"
            ok-text="确认"
            placement="left"
            @confirm="handleDelete(row)"
          >
            <u-tooltip title="删除">
              <u-button
                type="text"
                icon="delete"
                class="action-button"
                :disabled="row.status === 1"
              />
            </u-tooltip>
          </u-pop-confirm>
        </template>
      </u-table>
    </div>
  </div>
  <message-edit
    v-model:visible="editVisible"
    :current-model="currentRow"
    :current-mode="currentMode"
    @close="handleDrawerClose"
    @refreshTable="handleRefresh"
  />
  <message-view v-model:visible="viewVisible" :current-model="currentRow" @close="handleDrawerClose" />
</template>
<script>
import { ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import {
  message, DynamicsFilter, libs, hooks
} from '@bairong/vix'
import { status } from '@libs/data/enums'
import { getMessageListApi, changeTemplateStatusApi } from '@api/message'
import OneLineText from '@C/OneLineText.vue'
import AUTH_CODE from '@libs/data/const'
import filter from '@/filter'
import MessageEdit from './MessageEdit.vue'
import MessageView from './MessageView.vue'
import { messageColumns } from '../columns'

const { usePageList, usePermission } = hooks
const { parseTime } = libs.conversion

export default {
  name: 'MessageList',
  components: {
    DynamicsFilter, MessageEdit, OneLineText, MessageView
  },
  setup() {
    const store = useStore()
    const { hasAuth } = usePermission()
    const editVisible = ref(false)
    const viewVisible = ref(false)
    const currentRow = ref({})
    const currentMode = ref('add')
    const setting = ref([
      {
        name: 'key',
        label: '模板名称',
        type: 'input',
        placeholder: '请输入模板名称'
      },
      {
        name: 'companyId',
        label: '商户',
        type: 'select',
        options: [],
        props: { filterable: true },
        placeholder: '请选择商户',
        remoteMethod: () => new Promise(resolve => {
          store.dispatch('getCompanyOptions').then(res => {
            resolve(res.map(a => ({ ...a, value: a.companyId })))
          })
        })
      },
      {
        name: 'status',
        label: '状态',
        type: 'select',
        options: status,
        placeholder: '请选择模板状态'
      }
    ])

    const {
      listData, listQuery, getList, handleQuery, handlePageChange
    } = usePageList({
      getListApi: getMessageListApi,
      getQueryParameters: DynamicsFilter.libs.getQueryParameters
    })

    const handleTableChange = pagination => {
      const { current, pageSize, total } = pagination
      let nextCurrent = current
      if ((current - 1) * pageSize > total) {
        nextCurrent = Math.floor(total / pageSize) + 1
      }
      handlePageChange(nextCurrent, pageSize)
    }

    const handleView = (row, type) => {
      currentRow.value = row
      // currentMode.value = 'view';
      if (type === 'view') {
        viewVisible.value = true
      } else {
        editVisible.value = true
      }
    }

    const handleEdit = row => {
      currentRow.value = row || {}
      currentMode.value = row ? 'edit' : 'add'
      editVisible.value = true
    }

    const changeTemplateStatus = (params, msg) => {
      listQuery.loading = true
      changeTemplateStatusApi(params)
        .then(() => {
          message.success(`${msg}成功`)
          getList()
        })
        .catch(err => {
          listQuery.loading = false
          message.error(err.message || `${msg}失败`)
        })
    }

    const handleForbid = (row, status) => {
      const params = {
        smsTaskTemplateId: row.smsTaskTemplateId,
        status
      }
      const msg = status === 1 ? '启用模板' : '禁用模板'
      changeTemplateStatus(params, msg)
    }

    const handleDelete = row => {
      const params = {
        smsTaskTemplateId: row.smsTaskTemplateId,
        status: 3
      }
      const msg = '删除模板'
      changeTemplateStatus(params, msg)
    }

    onMounted(() => {
      getList()
    })

    const handleRefresh = (isFirst = false) => {
      if (isFirst) {
        handlePageChange(1)
      } else {
        getList()
      }
    }

    const getUsedStrategy = str => {
      if (Array.isArray(str)) {
        return str.join(',')
      }
      return str || ''
    }

    return {
      AUTH_CODE,
      hasAuth,
      viewVisible,
      editVisible,
      currentMode,
      currentRow,
      setting,
      listData,
      listQuery,
      messageColumns,
      handleQuery,
      parseTime,
      handleTableChange,
      handleView,
      handleEdit,
      handleForbid,
      handleDelete,
      handleDrawerClose: () => {
        currentRow.value = {}
        currentMode.value = 'add'
      },
      handleRefresh,
      getUsedStrategy,
      filter
    }
  }
}
</script>
<style lang="less"></style>
